Valid Anagram

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,

s = "anagram", t = "nagaram", return true.

s = "rat", t = "car", return false.

Note:

You may assume the string contains only lowercase alphabets.

Follow up:

What if the inputs contain unicode characters? How would you adapt your solution to such case?

Solution:

  1. public class Solution {
  2. public boolean isAnagram(String s, String t) {
  3. if (s == null || t == null || s.length() != t.length())
  4. return false;
  5. int[] arr = new int[128];
  6. for (int i = 0; i < s.length(); i++) {
  7. arr[(int)s.charAt(i)]++;
  8. arr[(int)t.charAt(i)]--;
  9. }
  10. for (int i = 0; i < arr.length; i++) {
  11. if (arr[i] != 0)
  12. return false;
  13. }
  14. return true;
  15. }
  16. }